/**
 * Created by Mark_ren on 2016/10/10.
 * 苟富贵、無相忘
 */
var express = require('express');
var router = express.Router();
var moment = require("moment");
var co = require('co');
var seqModule = require('./createModules');
var seq = new seqModule();


var formidable = require('formidable');
var getIP = require('./getIP');
var fs = require('fs');

//分页查询点播内容
router.get('/getMetVideoPage', function(req, res, next) {
    co(function () {
        var page=parseInt(req.query.page);
        var params={};
        var paramT={};
        var paramU={};
        var include=[{model:seq.metSortMenuModule}];
        paramT["include"]=include;
        if(req.query.id != undefined){
            params["id"]=req.query.id;
        }
        //模糊查询
        if(req.query.title != undefined && req.query.title != ""){
            paramU["$like"]="%"+req.query.title+"%";
            params["title"]=paramU;

        }
        if(req.query.picUrl != undefined){
            params["picUrl"]=req.query.picUrl;
        }
        if(req.query.url != undefined){
            params["url"]=req.query.url;
        }
        if(req.query.metSortId != undefined){
            params["metSortId"]=req.query.metSortId;
        }
        if(req.query.metSortTitle != undefined && req.query.metSortTitle != ""){
            params["metSortTitle"]={"$like":"%"+req.query.metSortTitle+"%"};
        }
        paramT["where"]=params;
        paramT["order"]=[["createTime",'DESC']];
        if(req.query.page != undefined && req.query.rows !=undefined){
            paramT["offset"]=parseInt(req.query.page);
            paramT["limit"]=parseInt(req.query.rows);
        }
        seq.metVideoMenuModule.findAndCountAll(paramT).then(function(result){
            res.json({"success":true,"page":page,"total":result.count,"result":result.rows});  });
    }).catch(function(e) {
        res.json({'success':false,'msg':'查询失败'});
        console.log(e);
    })
});
//查询
router.get('/getMetVideos', function(req, res, next) {
    co(function () {
        var params={};
        var paramT={};
        var paramU={};
        if(req.query.id != undefined){
            params["id"]=req.query.id;
        }
        //模糊查询
        if(req.query.title != undefined){
            paramU["$like"]="%"+req.query.title+"%";
            params["title"]=paramU;

        }
        if(req.query.picUrl != undefined){
            params["picUrl"]=req.query.picUrl;
        }
        if(req.query.url != undefined){
            params["url"]=req.query.url;
        }
        if(req.query.metSortId != undefined){
            params["metSortId"]=req.query.metSortId;
        }
        paramT["where"]=params;
        paramT["order"]=[["createTime",'DESC']];

        seq.metVideoMenuModule.findAll(paramT).then(function(result){
            res.json({"success":true,"result":result});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'查询失败'});
        console.log(e);
    })
});

//添加点播
router.get('/addMetVideo', function(req, res, next) {
    co(function () {
        seq.metVideoMenuModule.create(req.query).then(function(results){
            res.json({"success":true,"rows":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'添加失败'});
        console.log(e);
    })
});

//删除
router.get('/deleteMetVideo', function(req, res, next) {
    co(function () {
        var params=req.query.params;
        var arr=params.split(",");
        var paramT=[arr];
        seq.metVideoMenuModule.destroy({'where':{'id':paramT}}).then(function(results){
            res.json({"success":true,"msg":"删除成功","rows":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'删除失败'});
        console.log(e);
    })
});

//修改点播内容
router.get('/updateMetVideo', function(req, res, next) {
    co(function () {
        var params={};
        var paramT={};
        var paramU={'id':req.query.id};

        if(req.query.title != undefined){
            params["title"]=req.query.title;
        }
        if(req.query.picUrl != undefined){
            params["picUrl"]=req.query.picUrl;
        }
        if(req.query.url != undefined){
            params["url"]=req.query.url;
        }
        if(req.query.metSortId != undefined){
            params["metSortId"]=req.query.metSortId;
        }
        if(req.query.metSortTitle != undefined){
            params["metSortTitle"]=req.query.metSortTitle;
        }

        paramT["where"]=paramU;
        seq.metVideoMenuModule.update(params,paramT
        ).then(function(results){
            res.json({"success":true,"msg":"修改成功","rows":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'修改失败'});
        console.log(e);
    })
});

//添加图片
router.post('/addMetVideoImg', function(req, res, next) {
    co(function () {
        console.log(req.method);
        if (req.method.toLowerCase() == 'post') {
            // parse a file upload
            var form = new formidable.IncomingForm();
            //files = [],
            //fields = [];
            form.uploadDir = "public/img";
            form.type = true;
            form.on("progress", function (bytesReceived, bytesExpected) {
                console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                // 百分比
                var percent = Math.round(bytesReceived / bytesExpected * 100);
                console.log("percent:" + percent + "%");
                // 存入
                //sessions.setSession(req,res,opts);
            });
            form.parse(req, function (err, fields, files) {
                // res.render('index', { paths: [files.upload.name] });
                var imgType=files.picUrl.name.split(".");
                files.picUrl.name="video_"+moment().format("YYYYMMDDHHmmss"+"."+imgType[imgType.length-1]);
                fs.renameSync(files.picUrl.path, form.uploadDir + "/" + files.picUrl.name);
                fields.picUrl = files.picUrl.name;
                seq.metVideoMenuModule.create(fields).then(function (results) {
                    res.redirect(getIP+'metVideo/metVideoList.html');
                });
            });
        }
    }).catch(function(e) {
        res.json({'success':false,'msg':'添加失败'});
        console.log(e);
    })
});

//修改图片
router.post('/updateMetVideoImg', function(req, res, next) {
    co(function () {
        if (req.method.toLowerCase() == 'post') {
            // parse a file upload
            var form = new formidable.IncomingForm();
            //files = [],
            //fields = [];
            form.uploadDir = "public/img";
            form.type = true;
            form.on("progress", function (bytesReceived, bytesExpected) {
                console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                // 百分比
                var percent = Math.round(bytesReceived / bytesExpected * 100);
                console.log("percent:" + percent + "%");
                // 存入
                //sessions.setSession(req,res,opts);
            });
            form.parse(req, function (err, fields, files) {
                // res.render('index', { paths: [files.upload.name] });
                var paramT={};
                if(files.picUrl.name != ""){
                    var imgType=files.picUrl.name.split(".");
                    files.picUrl.name="video_"+moment().format("YYYYMMDDHHmmss"+"."+imgType[imgType.length-1]);
                    fs.renameSync(files.picUrl.path, form.uploadDir + "/" + files.picUrl.name);
                    fields["picUrl"]=files.picUrl.name;
                }
                var paramU={'id':fields.id};
                paramT["where"]=paramU;
                delete fields.id;

                seq.metVideoMenuModule.update(fields,paramT).then(function (results) {
                    res.redirect(getIP+'metVideo/metVideoList.html');
                });
            });
        }
    }).catch(function(e) {
        res.json({'success':false,'msg':'修改失败'});
        console.log(e);
    })
});

module.exports = router;